package com.javabasic.basic_learning;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see
 * @since Created by work on 2022/3/16 9:06 下午
 */
public class CustomClassLoader extends ClassLoader {

    String basePath;

    public CustomClassLoader(String basePath) {
        this.basePath = basePath;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        String fileName = basePath + name.replaceAll("\\.","/") + ".class";
//        InputStream is = getClass().getResourceAsStream(fileName);
//        if (null == is) {
//            return super.loadClass(name);
//        }
        InputStream is;
        byte[] bytes;
        try {
            is = new FileInputStream(fileName);
            bytes = new byte[is.available()];
            is.read(bytes);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ClassNotFoundException(name);
        }
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        HelloWorld helloWorld = new HelloWorld();
        System.out.println(helloWorld.getClass().hashCode());
        System.out.println(helloWorld.getClass().getClassLoader());
        System.out.println(helloWorld.getClass().getTypeName());
        System.out.println(helloWorld.getClass().getSimpleName());
        System.out.println(helloWorld.getClass());
//        String basePath = "/Users/mir/javaworks/javabasic/target/classes/";
        String basePath = "/Users/mir/javaworks/javabasic/src/main/java/";
        CustomClassLoader customClassLoader = new CustomClassLoader(basePath);
        Object instance = customClassLoader.loadClass(helloWorld.getClass().getTypeName()).newInstance();
        System.out.println(instance.getClass());
        System.out.println(instance.getClass().hashCode());
        System.out.println(instance.getClass().getClassLoader());
        System.out.println(instance instanceof HelloWorld);
    }
}
